package com.taotao.ToDoList;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class FragmentInput extends Fragment {
    private OnInputToDoItemListener onInputToDoItemListener;

    private EditText field_input;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_input, container, false);
        field_input = (EditText) view.findViewById(R.id.field_input);
        field_input.setOnKeyListener(new EditText.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER)) {
                    onInputToDoItemListener.onInputToDoItem(field_input.getText().toString());
                    field_input.setText("");
                    return true;
                }
                return false;
            }
        });
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            onInputToDoItemListener = (OnInputToDoItemListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnInputToDoItemListener");
        }
    }

    public interface OnInputToDoItemListener {
        public void onInputToDoItem(String item);
    }
}
